﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HundSunDBQry
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string date = "";
            string path = "./data";
            if (args.Length > 0)
            {
                path = args[0];
            }
            if (args.Length > 1)
            {
                date= args[1];
            }
            if (date=="")
            {
                date = DateTime.Now.ToString("yyyyMMdd");
            }
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filePath = Path.Combine(path, $"{date}.xlsx");
            int count=0;
            while (!File.Exists(filePath))
            {
                var rsp=HundsunDB.qryFundJour(date);
                if (rsp.code==0&&rsp.data.Count>0)
                {
                    DataTable dataTable = new DataTable();
                    dataTable.Columns.Add("营业部", typeof(string)); // 替换为实际的列名和数据类型
                    dataTable.Columns.Add("银行", typeof(string));
                    dataTable.Columns.Add("业务名称", typeof(string));
                    dataTable.Columns.Add("发生金额", typeof(double));
                    dataTable.Columns.Add("日期", typeof(string));
                    dataTable.Columns.Add("时间", typeof(string));
                    dataTable.Columns.Add("交易日", typeof(string));
                    foreach (var item in rsp.data)
                    {
                        RspQryFundJour fundJour = JsonConvert.DeserializeObject<RspQryFundJour>(item.ToString());
                        dataTable.Rows.Add(fundJour.Department, fundJour.BankName, fundJour.BusinessName, double.Parse(fundJour.OccurBalance), fundJour.Date, fundJour.Time, fundJour.TradingDay);
                    }
                    try
                    {
                        ExcelHelp.writeExcel(dataTable, filePath);
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    } 
                }
                count++;
                Console.WriteLine($"{DateTime.Now.ToString("yyyyMMDD HH:mm:ss")}>> 获取数据失败，当前尝试第{count}次，共10次");
                if (count >= 10)
                {
                    break;
                }
                Thread.Sleep(1000*60*10);
            }
            Console.WriteLine($"程序结束");
        }
    }
}
